package com.huangpuweb.api.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huangpuweb.api.model.dto.CommonDataToken;
import com.huangpuweb.api.util.HttpUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 门户共享数据Api
 */
@RestController
@RequestMapping("/common/data")
public class CommonDataApi {

        //客户端账号标识,请修正为实际值
        private static String AppKey = "72244936-7a92-4508-81cb-d61c80104270";
        //客户端账号密码,请修正为实际值
        private static String AppSecret = "fe794d93-9f70-4cfc-8f3f-120b0205610b";
        //认证平台地址，具备token接口，只需要配置到认证平台应用系统名即可,请修正为实际值
        //本地测试地址
        private static String SSOUrl = "http://172.82.2.1/epoint-sso-web/rest/oauth2/token";

        //生产地址:（这里由于政务网与172.82.2.1是通的，为了方便省去了开173网段的策略，直接用了）
        //private static String SSOUrl = "http://172.82.2.1/epoint-sso-web/rest/oauth2/token";

    /**
     * 获取获取Token
     */
    private static CommonDataToken getToken(){
            List<NameValuePair> params = new ArrayList<>();
            NameValuePair pair = new BasicNameValuePair("grant_type", "client_credentials");
            NameValuePair pair2 = new BasicNameValuePair("client_id", AppKey);
            NameValuePair pair3 = new BasicNameValuePair("client_secret", AppSecret);
            params.add(pair);
            params.add(pair2);
            params.add(pair3);
            String postForString = HttpUtil.postWithParamsForString(SSOUrl, params);
            JSONObject jsonObject = JSON.parseObject(postForString);
            CommonDataToken commonDataToken = JSONObject.parseObject(jsonObject.get("custom").toString(), CommonDataToken.class);
            return commonDataToken;
    }


    /**
     * 获取公交站数据
     * @param :lineid: 公交线路id;  name: 公交车名
     *
     * @throws Exception
     */
    @RequestMapping("/getBusStops")
     public Object getBusStops(@RequestBody  Map<String,Object> params){
        String Url = "http://172.82.2.1/kong/share/gjzdxxcxjk";
        //调用API的参数,请修正为实际值
    /*    Map params = new HashMap<>();
        //公交路线id
        params.put("lineid","1");
        //公交车名称
        params.put("name","70路");*/
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(Url);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + getToken().getAccess_token());
        //注意这里需要设置编码格式
        httpPost.setEntity(new StringEntity(JSONObject.toJSONString(params),"UTF-8"));
        String responseContent = null;
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");

        } catch (IOException e) {
            e.printStackTrace();
            JSONObject result =  new JSONObject();
            result.put("msg","调用第三方接口【"+ Url +"】异常: " + e);
            result.put("code","666");
            result.put("data","");
            return result;
        }
        return JSONObject.parse(responseContent);
    }


    /**
     * 获取公交车实时数据
     * @param
     * @throws Exception
     */
    @RequestMapping("/getBuses")
    public Object getBuses(@RequestBody Map<String,Object> params) {
        String Url = "http://172.82.2.1/kong/share/gjclssxxcx";
      /*  Map params = new HashMap<>();
        params.put("lineid","092600");
        params.put("name","926路");
        params.put("stopid",5);
        params.put("direction",0);*/

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(Url);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Authorization", "Bearer " + getToken().getAccess_token());
        StringEntity postingString = new StringEntity(JSON.toJSONString(params),"UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        String content = null;
        try {
            HttpResponse response = httpClient.execute(post);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            JSONObject result =  new JSONObject();
            result.put("msg","调用第三方接口"+ Url +"异常: " + e);
            result.put("code","666");
            result.put("data","");
            return result;
        }
        return JSONObject.parse(content);
    }

    /**
     * 公交车基本信息查询接口
     */
    @RequestMapping("/getBusesInfo")
    public Object getBusesInfo(@RequestBody Map<String,Object> params) {
        String Url = "http://172.82.2.1/kong/share/gjjbxxcx";
      /*  Map params = new HashMap<>();

        params.put("name","926路");
      */

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(Url);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Authorization", "Bearer " + getToken().getAccess_token());
        StringEntity postingString = new StringEntity(JSON.toJSONString(params),"UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        String content = null;
        try {
            HttpResponse response = httpClient.execute(post);
            content = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            JSONObject result =  new JSONObject();
            result.put("msg","调用第三方接口"+ Url +"异常: " + e);
            result.put("code","666");
            result.put("data","");
            return result;
        }
        return JSONObject.parse(content);
    }

}
